<template>
  <div class="app-container">
    <div style="padding: 20px;">
      <el-row>
        <el-col :span="4">
          <strong style="font-size: 20px;">
            新增/修改
          </strong>
        </el-col>
      </el-row>

      <div style="padding:20px">
        <el-form ref="form" :model="form" label-width="150px">
          <el-form-item label="用户名">
            <el-input v-model="form.username" :disabled="true" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="小队" prop="squad">
            <el-select
              v-model="form.squad"
              filterable
              clearable
              @change="$forceUpdate()"
            >
              <el-option
                v-for="item in squads"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否在职">
            <el-checkbox v-model="form.enabled" />
          </el-form-item>
          <el-form-item label="场所管理员">
            <el-checkbox v-model="form.isManager" />
            <div class="help-text" style="display: flex;">
              <div>
                <p class="el-icon-info" />
              </div>
              <div>
                <p v-html="'设置为经理之后，用户在小程序可以操作门店所有数据'" />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: Number(this.$route.params.id),
      store: '',
      form: {
        username: '',
        squad: null,
        name: '',
        phone: '',
        isManager: false,
        enabled: true
      },
      staffs: [],
      squads: []
    }
  },
  created() {
    this.store = localStorage.getItem('storeId')
    if (this.id) {
      if (this.store > 0) {
        this.axios.get(`/store/${this.store}/staffs/${this.id}`, { params: {
          '@expands': `['entity.user']`
        }}).then((res) => {
          this.form.username = res.data.user?.__metadata.username
          this.form.squad = res.data.squad?.id
          this.form.name = res.data.name
          this.form.phone = res.data.phone
          this.form.isManager = res.data.isManager
          this.form.enabled = res.data.enabled
        })
      }
    }
    this.getSquads()
    this.getStaffs()
  },
  methods: {
    getStaffs() {
      this.axios.get(`/store/${this.store}/staffs`, {
        params: {
          limit: 10000000
        }
      }).then((res) => {
        this.staffs = res.data
      })
    },
    getSquads() {
      this.axios.get(`/store/${this.store}/squads`, {
        params: {
          limit: 10000000
        }
      }).then((res) => {
        this.squads = res.data
      })
    },
    onSubmit() {
      console.log('formData', this.form.extraData)
      if (this.store > 0) {
        if (!this.form.name) {
          this.$message.error('请填写名称！')
          return
        }
        if (!this.form.phone) {
          this.$message.error('请填写电话！')
          return
        }
        if (this.id) {
          const loading = this.$loading({
            lock: true,
            text: '数据交互中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.axios.put(`/store/${this.store}/staffs/${this.id}`, this.form).then((res) => {
            this.$message.success('修改成功！')
            this.$router.go(-1)
            loading.close()
          })
        } else {
          const loading = this.$loading({
            lock: true,
            text: '数据交互中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.axios.get(`/store/${this.store}/users`, { params: {
            '@filter': `entity.getUsername() == "${this.form.phone}"`,
            '@expands': '["entity.staffs"]'
          }}).then((res) => {
            if (res.data.length > 0) {
              const user = res.data[0]
              if (!user.enabled) {
                loading.close()
                this.$message.error('此电话用户名账号已停用！')
                return
              }
              const storeStaff = user.staffs.find(v => v.__metadata.store.id === parseFloat(this.store))
              if (storeStaff) {
                loading.close()
                this.$message.error('此电话用户名在改门店已建立员工信息！')
                return
              }
              const form = JSON.parse(JSON.stringify(this.form))
              form.user = user.id
              this.axios.post(`/store/${this.store}/staffs`, form).then(staff => {
                loading.close()
                this.$message.success('创建成功！')
                this.$router.go(-1)
              })
            } else {
              this.axios.post(`/store/${this.store}/users`, {
                username: this.form.phone,
                email: this.form.phone + '@email.com',
                enabled: true,
                plainPassword: 'nightkeeper'
              }).then(user => {
                this.form.user = user.data.id
                this.axios.post(`/store/${this.store}/staffs`, this.form).then(staff => {
                  loading.close()
                  this.$message.success('创建成功！')
                  this.$router.go(-1)
                })
              })
            }
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.help-text {
  display: flex;
  p {
    color: gray;
    line-height: 1.3em;
  }
  div {
    padding: 0 3px;
  }
}
</style>
